package com.lutzyt.delivery.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lutzyt.delivery.bean.Role;
import com.lutzyt.delivery.mapper.RoleDAO;
import com.lutzyt.delivery.service.RolePermissionService;
import com.lutzyt.delivery.service.RoleService;
import com.lutzyt.delivery.service.UserRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author zyt
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class RoleServiceImpl extends ActionServiceImpl<RoleDAO, Role> implements RoleService {

  public static final String ROLE_ID = "role_id";
  private RoleDAO roleDAO;
  private RolePermissionService rolePermissionService;
  private UserRoleService userRoleService;

  @Transactional(readOnly = true)
  @Override
  public Role findById(Integer id) {
    return roleDAO.selectById(id);
  }

  @Transactional(readOnly = true)
  @Override
  public IPage<Role> findByPage(int pageNum, int pageSize) {
    return roleDAO.selectPage(new Page<>(pageNum, pageSize), null);
  }

  @Override
  public void insert(Role role) {
    roleDAO.insert(role);
  }

  @Override
  public void update(Role role) {
    roleDAO.updateById(role);
  }

  @Override
  public void deleteById(Integer id) {
    if (userRoleService.query().eq(ROLE_ID, id).count() > 0) {
      throw new RuntimeException("该角色已经被分配，请收回后在操作");
    }
    roleDAO.deleteById(id);
    rolePermissionService.update().eq(ROLE_ID, id).remove();
  }

  @Override
  public void deleteByIds(List<String> ids) {
    if (userRoleService.query().in(ROLE_ID, ids).count() > 0) {
      throw new RuntimeException("该角色已经被分配，请收回后在操作");
    }
    roleDAO.deleteBatchIds(ids);
    rolePermissionService.update().in(ROLE_ID, ids).remove();
  }

  @Autowired
  public void setRoleDAO(RoleDAO roleDAO) {
    this.roleDAO = roleDAO;
  }

  @Autowired
  public void setUserRoleService(UserRoleService userRoleService) {
    this.userRoleService = userRoleService;
  }

  @Autowired
  public void setRolePermissionService(RolePermissionService rolePermissionService) {
    this.rolePermissionService = rolePermissionService;
  }
}